/**
 * Copyright (C) 2009-2012, KingHool.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses.
 */
package com.kinghool.smodel.io.bean.xml;


import com.kinghool.smodel.IXmlModel;
import com.kinghool.smodel.ModelService;
import com.kinghool.smodel.io.bean.BaseBeanChannelProvider;
import com.kinghool.smodel.io.bean.IBeanChannelProvider;
import com.kinghool.smodel.io.bean.annotation.AnnotationBeanChannelProvider;
import com.kinghool.smodel.io.xml.IDocumentProvider;

/**
 * 
 * @Author Allen Deng(dengtailin@gmail.com) 
 */
public class XmlBeanChannelProvider extends BaseBeanChannelProvider implements IBeanChannelProvider {

	private IDocumentProvider provider;
	private BeanModelMapping mapping;

	public XmlBeanChannelProvider(Class<?> beanClass, IDocumentProvider provider) {
		super(beanClass);
		this.provider = provider;
	}

	public BeanModel getBeanModel(Class<?> beanClass) {
		try {
			BeanModel beanModel = getMapping().getBeanModel(beanClass.getName());
		    
		    if (beanModel != null) {
				return beanModel;
		    }
		    		    
		    //TODO
		    throw new RuntimeException();
		} catch (Exception e) {//TODO
			throw new RuntimeException(e);
		}
	}
	
	private BeanModelMapping getMapping() {
		try {
			if (mapping == null) {
				IXmlModel mappingModel = ModelService.loadFromXML(provider);
			    mapping = ModelService.flushToBean(mappingModel, new AnnotationBeanChannelProvider(BeanModelMapping.class));
			}
		} catch (Exception e) {//TODO
			throw new RuntimeException(e);
		}
		return mapping;
	}

	protected BeanModel getAutoChildBeanModel(Class<?> clazz) {	     
		BeanModel beanModel = getMapping().getBeanModel(clazz.getName());
		if (beanModel == null) {
			return new AnnotationBeanChannelProvider(clazz).getBeanModel(clazz);
		}
		return beanModel;
	}
}
